package ozu.project.regions;

import ozu.project.OzuDice;
import ozu.project.OzuPlayer;

import java.awt.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Observable;


public class OzuRegion extends Observable{
    private int armySize;
    private OzuPlayer player = new OzuPlayer("none", Color.DARK_GRAY);
    private String name;
    private Collection<OzuRegion> neighbours = new ArrayList<>();
    private boolean isFocused;
    private static final int INIT_ARMY_SIZE = 3;

    public OzuRegion(String name) {
        this.name = name;
        this.armySize = INIT_ARMY_SIZE;
    }

    public String getName() {
        return name;
    }

    public Collection<OzuRegion> getNeighbours() {
        return neighbours;
    }

    public int getArmySize() {
        return armySize;
    }

    public void setArmySize(int armySize) {
        this.armySize = armySize;
        setChanged();
        notifyObservers();
    }

    public void addArmy(int armies){
        this.armySize += armies;
        setChanged();
        notifyObservers();
    }

    public OzuPlayer getOwner() {
        return player;
    }

    public void setOwner(OzuPlayer player) {
        this.player = player;
        setChanged();
        notifyObservers();
    }

    public void addNeighbour(OzuRegion region){
        neighbours.add(region);
    }

    public boolean isNeighbour(OzuRegion region){
        return neighbours.contains(region);
    }

    //The region is focused if the player has clicked it's RegionComponent.
    public boolean isFocused() {
        return isFocused;
    }

    public void setFocused(boolean focused) {
        isFocused = focused;
        setChanged();
        notifyObservers();
    }

    public int attack(OzuRegion attacked, int attackSize){
        ArrayList<OzuDice> attackerDices = new ArrayList<>();
        ArrayList<OzuDice> defenderDices = new ArrayList<>();
        for (int i = 0; i < attackSize; i++) {
            attackerDices.add(new OzuDice());
        }
        for (int i = 0; i < (attacked.armySize >= 2 ? 2 : 1); i++){
            defenderDices.add(new OzuDice());
        }

        int attackerLoss = 0;
        int defenderLoss = 0;
        while (!(attackerDices.isEmpty() || defenderDices.isEmpty())){
            if (popMax(attackerDices) > popMax(defenderDices)) defenderLoss++;
            else attackerLoss++;
        }
        this.addArmy(-attackerLoss);
        attacked.addArmy(-defenderLoss);
        return attackerLoss;
    }

    //Consumes and returns the dice with the highest value. Used to decide losses in a battle.
    private int popMax(ArrayList<OzuDice> dices){
        OzuDice max = dices.get(0);
        for (OzuDice dice : dices) {
            if (max.getValue() < dice.getValue()) max = dice;
        }
        dices.remove(max);
        return max.getValue();
    }

}
